package com.xykj.enterprise.wechat.ext.api.contacts.tag;

import com.xykj.enterprise.wechat.bean.ext.contacts.tag.AddTagUserVo;
import com.xykj.enterprise.wechat.ext.service.contacts.ContactsTagService;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Slf4j
@Function(description = "增加标签成员", parameters = {
        @Parameter(name = "access_token", type = Type.String, description = "access_token", required = true),

        @Parameter(name = "tagid", type = Type.Integer, description = "标签id，非负整型，指定此参数时新增的标签会生成对应的标签id，不指定时则以目前最大的id自增。", required = true),
        @Parameter(name = "userlist", type = Type.String, description = "企业成员ID列表，注意：userlist、partylist不能同时为空，单次请求个数不超过1000", required = false),
        @Parameter(name = "partylist", type = Type.String, description = "企业部门ID列表，注意：userlist、partylist不能同时为空，单次请求个数不超过100", required = false),
})
@Component
public class AddTagUser implements Action {

    @Autowired
    private ContactsTagService contactsTagService;

    @Override
    public Response execute(Request request) throws Exception {
        Integer tagid = request.getInteger("tagid");
        String userlist = request.getString("userlist");
        String partylist = request.getString("partylist");
        if (tagid == null) {
            return Response.fail("参数错误！");
        }
        if (userlist == null && partylist == null) {
            return Response.fail("参数错误！");
        }
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("tagid", tagid);
        if (userlist != null) {
            String[] userlistSplit = userlist.split(",");
            params.put("userlist", userlistSplit);
        }
        if (partylist != null) {
            String[] partylistSplit = partylist.split(",");
            params.put("partylist", partylistSplit);
        }
        AddTagUserVo rsp = contactsTagService.addTagUser(
                request.getString("access_token"), params
        );
        if (rsp.getErrcode() != 0) {
            return Response.fail(rsp.getErrmsg());
        }
        return Response.success().put("data", rsp);
    }
}
